﻿using BLL.DisinfectBLL;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using YQFK.Models;
using System.IO;
using BLL.Base;
using YQFK.Helper;
using BLL.RYGL;
using YQFK.Filter;

namespace YQFK.Controllers
{
    /// <summary>
    /// 消毒记录
    /// </summary>
    [ActonFilter]
    [ErrorFilter]
    public class DisinfectController : ApiController
    {
        /// <summary>
        /// 消毒记录
        /// </summary>
        private readonly DisinfectBLL _disinfectBLL;
        /// <summary>
        /// 附件管理
        /// </summary>
        private readonly FileBLL _fileBll;
        /// <summary>
        /// 编码管理
        /// </summary>
        private readonly CodeBLL _codeBll;
        /// <summary>
        /// 人员管理
        /// </summary>
        private readonly EmployeeBLL _employeeBLL;
        public DisinfectController()
        {
            _disinfectBLL = new DisinfectBLL();
            _fileBll = new FileBLL();
            _codeBll = new CodeBLL();
        }

        //[Route("api/Disinfect/Add")]
        /// <summary>
        /// 新增消毒记录
        /// </summary>
        /// <param name="model">消毒记录</param>
        /// <returns></returns>
      
        public object Add()
        {
            try
            {
                var json = HttpContext.Current.Request["json"];
                DisinfectModel model = JsonConvert.DeserializeObject<List<DisinfectModel>>("["+ json+"]").FirstOrDefault();
                if (model == null) throw new Exception("无法解析数据");
                model.Id = Guid.NewGuid();
                model.CreateTime = DateTime.Now;
                bool success = _disinfectBLL.Add(model);
                HttpFileCollection files = HttpContext.Current.Request.Files;
                if (files !=null && files.Count>0)
                {
                    List<FileModel> insertList = new List<FileModel>();
                    for (int i = 0; i < files.Count; i++)
                    {
                        if(files[i].ContentLength < 1) continue;
                        HttpPostedFile file = files[i];
                        var filename = file.FileName;
                        var fileExtend = filename.Substring(filename.LastIndexOf(".")).ToLower();


                        var serverPath = $"~/AppFile/Disinfect/{DateTime.Now.ToString("yyyy-MM-dd")}/";
                        var savePath=HttpContext.Current.Server.MapPath(serverPath);
                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }
                        string realName = Guid.NewGuid() + fileExtend;
                        file.SaveAs(savePath + realName);
                        FileModel insertModel = new FileModel()
                        {
                            Id = Guid.NewGuid(),
                            CreateTime = DateTime.Now,
                            CreateUserId = model.CreateUserId,
                            CreateUserName = model.CreateUserName,
                            FileName = realName,
                            FileType = fileExtend,
                            RealName = filename,
                            RecId = model.Id.ToString(),
                            FilePath = serverPath + realName
                        };
                        insertList.Add(insertModel);
                    }

                    _fileBll.SaveFile(insertList);
                }
             

                if (success)
                    return new ResponeModel();
                else
                    return new ResponeModel(-1, "操作失败");
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页个数</param>
        /// <param name="deptId">组织机构Id</param>
        /// <param name="userId">消毒人员Id</param>
        /// <param name="areaId">消毒区域Id</param>
        /// <returns></returns>
       [HttpPost]
        //[Route("api/Disinfect/GetPagedList")]
        public object GetPagedList(JObject jitem)
        {
            try
            {
                int pageIndex = Convert.ToInt32(jitem["pageIndex"]);
                int pageSize = Convert.ToInt32(jitem["pageSize"]); 
                string deptId = jitem["deptId"]?.ToString();
                string userId = jitem["userId"]?.ToString();
                string userName = jitem["userName"]?.ToString();
                string areaName = jitem["areaName"]?.ToString();
                string startTime = jitem["startTime"]?.ToString();
                string endTime = jitem["endTime"]?.ToString();
                int allCount = 0;
                List<DisinfectModel> data = _disinfectBLL.GetPagedList(pageIndex, pageSize, deptId, userId, areaName,startTime,endTime, userName, out allCount).ToList();
                //获取附件信息
                List<FileModel> files = _fileBll.GetFile(data.Select(x => x.Id).ToList()).ToList();
                files.ForEach(file => {
                    file.FilePath = Url.Content(file.FilePath);
                });
                data.ForEach(p => {
                    p.Files = files.Where(x => x.RecId == p.Id.ToString()).ToList();
                });
                return new ResponeModel(0, "查询成功", data, allCount);
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="jitem">主键</param>
        /// <returns></returns>
        [HttpPost]
        //[Route("api/Disinfect/Del")]
        public object Del(JObject  jitem)
        {
            try
            {
                if (jitem["id"] ==null)
                    throw new ArgumentNullException("id不能为空");
                string id = jitem["id"].ToString();
                if (jitem["userid"] == null)
                    throw new ArgumentNullException("userid不能为空");
                string userid = jitem["userid"].ToString().ToUpper();
                EmployeeModel employee =  _employeeBLL.GetAsync(Guid.Parse(userid)).Result;
                if (employee.EmployeeType!= "管理人员")
                {
                    return new ResponeModel(-1, "非管理人员无法删除数据");
                }
                if (_disinfectBLL.Del(id))
                     return new ResponeModel(0, "操作成功");
                else
                    return new ResponeModel(0, "操作失败");
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取编码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        //[Route("api/Disinfect/GetArea")]
        public object GetArea()
        {
            try
            {
                List<CodeModel> codeList = _codeBll.GetArea("消毒区域");
                return new ResponeModel(codeList);
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="jitem"></param>
        /// <returns></returns>
        [HttpPost]
        //[Route("api/Disinfect/GetDetail")]
        public object GetDetail(JObject jitem)
        {
            try
            {
                if (jitem["id"] == null)
                    throw new ArgumentNullException("id不能为空");
                DisinfectModel model = _disinfectBLL.GetDetail(jitem["id"].ToString());
                //获取附件信息
                List<FileModel> files = _fileBll.GetFile(new List<Guid>() { model.Id}).ToList();
                files.ForEach(file => {
                    file.FilePath = Url.Content(file.FilePath);
                });
                model.Files = files;
                return new ResponeModel(model);
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        //[Route("api/Disinfect/Update")]
        public object Update(DisinfectModel model)
        {
            try
            {
                if (_disinfectBLL.Update(model))
                    return new ResponeModel();
                else
                    return new ResponeModel(-1, "操作失败");
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        //[Route("api/Disinfect/FileUpload")]
        public object FileUpload()
        {
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                string recid = request["recid"];
                string deleteids = request["deleteids"];
                string userid = request["userid"];
                string username = request["username"];

                HttpFileCollection files = request.Files;
                if (files != null && files.Count > 0)
                {
                    List<FileModel> insertList = new List<FileModel>();
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                        var filename = file.FileName;
                        var fileExtend = filename.Substring(filename.LastIndexOf(".")).ToLower();
                        var serverPath = $"~/AppFile/Disinfect/{DateTime.Now.ToString("yyyy-MM-dd")}/";
                        var savePath = HttpContext.Current.Server.MapPath(serverPath);
                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }
                        string realName = Guid.NewGuid() + fileExtend;
                        file.SaveAs(savePath + realName);
                        FileModel insertModel = new FileModel()
                        {
                            Id = Guid.NewGuid(),
                            CreateTime = DateTime.Now,
                            CreateUserId =userid,
                            CreateUserName =username,
                            FileName = realName,
                            FileType = fileExtend,
                            RealName = filename,
                            RecId = recid,
                            FilePath = serverPath + realName
                        };
                        insertList.Add(insertModel);
                    }

                    _fileBll.SaveFile(insertList);
                }
                if (!string.IsNullOrWhiteSpace(deleteids))
                    _fileBll.Delete(deleteids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                return new ResponeModel();
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        //[Route("api/Disinfect/FileUpload")]
        public object AddCode(CodeModel model)
        {
            model.Id = Guid.NewGuid().ToString();
            try
            {
                if (_codeBll.AddCode(model))
                    return new ResponeModel();
                else
                    return new ResponeModel(-1, "操作失败");
            }
            catch (Exception ex)
            {
                WriteLog.AddLog(ex, HttpContext.Current.Request);
                return new ResponeModel(-1, $"操作失败：{ex.Message}");
            }
        }
    }
}